/**
 * Created by jt on 2017/5/6.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/jquery.jqGrid.src.js";

App.init();
var token = sessionStorage.getItem('token');
var grdId = getArgs().id;
var grdTyp = getArgs().sts;
var grdRul = '0';  // 默认最低单价评标
var currTyp = {};  // 币种
if (token == null || token =='') {
    location.href = HOST_FRT+'/logins/login.html';
}

let parmTyps = 'CURR_TYP';
$.ajax({
    url: HOST_ADDR + '/cpmp/comParm/getByParmTyp/' + 'CURR_TYP',
    type: 'get',
    dataType: 'json',
    async: false,
    headers: {'access_token': token, 'login_type': 'ums'},
    contentType: 'application/json',
    success: function (resp) {
        if (!resp.success) {
            alert(resp.msgCod + " - " + resp.msgInf);
            console.log(resp.msgCod + " - " + resp.msgInf);
            return;
        }
        if (jQuery.isArray(resp.data)) {
            for (var i = 0; i < resp.data.length; i++) {
                currTyp[resp.data[i].parmCod] = resp.data[i].parmMemo;
            }
        }
    },
    error: function (err) {
        console.log(err);
    }
})

jQuery.ajax({
    url: HOST_ADDR + '/cpmp/bidProjOnMngForExpt/viewGrdInf/' + grdId,
    type: 'get',
    dataType: 'json',
    contentType: "application/json",
    headers: { 'access_token': token, 'login_type': 'ums'},
    success: function (resp) {
        if(resp.success && resp.msgCod=='S0000'){
            console.log(resp);
            if(typeof (resp.data.projInf.grdRul)!='undefined' && resp.data.projInf.grdRul!=null && resp.data.projInf.grdRul!='' ){
                grdRul = resp.data.projInf.grdRul;
            }
            resp.data.projInf.projNam!=null  && $(".J_projNam").html(resp.data.projInf.projNam);

            if(grdRul=='0'){  // 最低单价评标
                $('.mygrid2').parent().removeClass("hide");
                grdLowestUnitPrice(resp.data.list);
            }else if(grdRul=='2'){ // 最低总价评标
                $('.mygrid3').parent().removeClass("hide");
                grdLowestSumPrice2(resp.data.list);
            }else{
                // $('.mygrid4').parent().removeClass("hide");
                // grdAll(list);
            }
        }else{
            alert(resp.msgCod + ' ' + resp.msgInf);
            return;
        }
    },
    error: function (err) {
        console.log(err);
    }
});

// 币种格式化
function currTypFmatter(cellvalue, options, rowObject){
    if(typeof(cellvalue)=='undefined' || cellvalue==""){
        return "";
    }
    return currTyp[cellvalue];
}


// 最低单价评标
function grdLowestUnitPrice(datalist){
    var totalLines = 1;  // 总数据行
    var matinfo = datalist;
    for(var i=0;i<datalist.length;i++){
        totalLines+=2;
    }
    jQuery("#mygrid2").jqGrid({
        width:'100%',
        dataType:'local',
        width:'100%',
        height: 250,
        colNames:['ID','物料编码','物料名称', '计量单位', '招标数量','交货地址','交货日期','备注'],
        colModel:[
            {name:'id',index:'id', width:50,hidden: true},
            {name:'matCod',index:'matCod', width:80},
            {name:'matNam',index:'matNam', width:150},
            {name:'matUnt',index:'matUnt', width:80,align:"center"},
            {name:'pchsNum',index:'pchsNum', width:80,align:"center"},
            {name:'dlvAdr',index:'dlvAdr', width:80},
            {name:'dlvDte',index:'dlvDte', width:120,align:"center"},
            {name:'memo',index:'memo', width:150}
        ],
        multiselect: false,
        subGrid: true,
        fitColumns: true,
        shrinkToFit: true,
        altRows: true,
        // define the icons in subgrid
        subGridOptions: {
            "plusicon"  : "ui-icon-triangle-1-e",
            "minusicon" : "ui-icon-triangle-1-s",
            "openicon"  : "ui-icon-arrowreturn-1-e",
            "reloadOnExpand" : true,
            "selectOnExpand" : true
        },
        subGridRowColapsed:function(subgrid_id, row_id){
            var subgrid_table_id = subgrid_id+"_t";
            if($("#"+subgrid_table_id)[0].p.savedRow.length){
                $("#"+subgrid_table_id).jqGrid("saveCell", $("#"+subgrid_table_id)[0].p.savedRow[0].id, $("#"+subgrid_table_id)[0].p.savedRow[0].ic)
            }
            // var subids = $("#"+subgrid_table_id).jqGrid('getDataIDs');
            for(var m=0;m<matinfo[row_id-1].qotInfs.length;m++){
                var subrowid = m+1;
                var rowinfo = matinfo[row_id-1].qotInfs[m];
                rowinfo.id = subrowid;
                rowinfo.isRcmd = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).isRcmd;
                rowinfo.grdRsn = $("#"+subgrid_table_id).jqGrid("getRowData",subrowid).grdRsn;
            }
        },
        subGridRowExpanded: function(subgrid_id, row_id) {
            var subgrid_table_id, pager_id, lastsel;
            subgrid_table_id = subgrid_id+"_t";
            pager_id = "p_"+subgrid_table_id;
            $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
            jQuery("#"+subgrid_table_id).jqGrid({
                datatype: "local",
                height: '100%',
                colNames: ['id','供应商ID','供应商','是否推荐中标','排名','币种','币种hidden','汇率','投标价格','应标数量','合计','应标交货日期','品牌','备注'],
                colModel: [
                    {name:"id",index:"id",hidden:true},
                    {name:"splrId",index:"splrId",hidden:true},
                    {name:"splrNam",index:"splrNam",width:200, sortable:false},
                    {name:"isLowest",index:"isLowest",width:80,align:"center",sortable:false},
                    {name:"grdOrd",index:"grdOrd",width:80,align:"center",sortable:false, formatter:'number'},
                    {name:"currTypFmt",index:"currTypFmt",width:70,align:"center", sortable:false,formatter: currTypFmatter},
                    {name:"currTyp",index:"currTyp",hidden:true},
                    {name:"exRat",index:"exRat",hidden:true},
                    {name:"uniPri",index:"uniPri",width:80,align:"center", sortable:false},
                    {name:"splNum",index:"splNum",width:80,align:"center", sortable:false},
                    {name:"ttlPri",index:"ttlPri",width:100,align:"center", sortable:false},
                    {name:"tendDlvDte",index:"tendDlvDte",width:110,align:"center", sortable:false},
                    {name:"matBnd",index:"matBnd",width:80,align:"center", sortable:false},
                    {name:"grdRsn",index:"grdRsn",width:100,align:"center", sortable:false}
                ],
                fitColumns: true,
                shrinkToFit: true,
                altRows: true,
                cellEdit: false,
                cellsubmit: 'clientArray',
                onSelectRow : function(id) {
                    if (id && id !== lastsel) {
                        jQuery("#"+subgrid_table_id).jqGrid('saveRow', lastsel);
                        lastsel = id;
                    }
                },
                afterEditCell: function(a, b, c, d, e) { },
                formatCell: function(a, b, c, d, e) { },
                beforeSubmitCell: function(a, b, c, d, e) { },
                beforeSaveCell: function(a, b, c, d, e) { },
                afterSaveCell: function(a, b, c, d, e) { }
            });
            for(var m=0;m<matinfo[row_id-1].qotInfs.length;m++){
                totalLines+=1;
                var subrowid = m+1;
                var rowinfo = matinfo[row_id-1].qotInfs[m];
                rowinfo.isLowest = m==0 ? "是":"否";
                rowinfo.grdOrd = rowinfo.grdOrd ? rowinfo.grdOrd : m+1;
                rowinfo.matBnd = rowinfo.matBnd ? rowinfo.matBnd : '';
                rowinfo.tendDlvDte = rowinfo.tendDlvDte ? (new Date(rowinfo.tendDlvDte)).Format("yyyy-MM-dd") : '';
                rowinfo.currTypFmt = rowinfo.currTyp;
                rowinfo.ttlPri = rowinfo.ttlPri ? rowinfo.ttlPri : 0;
                $("#"+subgrid_table_id).jqGrid('addRowData', subrowid, rowinfo);
                $("#"+subgrid_table_id+" #"+subrowid).data("rowinfo",rowinfo);
            }
        }
    });
    for ( var i = 0; i < matinfo.length; i++){
        var rowid = i+1;
        matinfo.matId = matinfo.matId ? matinfo.matId : rowid;
        matinfo[i].dlvDte = matinfo[i].dlvDte ? (new Date(matinfo[i].dlvDte)).Format("yyyy-MM-dd") : '';
        $("#mygrid2").jqGrid('addRowData', rowid, matinfo[i]);
        $("#mygrid2>tbody>tr#"+rowid+">td").trigger("click");  // 报价信息展开
    }
    $("#mygrid2>tbody>tr.jqgrow").addClass("bg-lightgray");

    function resize(){
        var table_id = "mygrid2";
        var ids = $("#"+table_id).jqGrid("getDataIDs");
        for(var i=0;i<ids.length;i++){
            var subgrid_table_id = table_id+"_"+ids[i]+"_t";
            if($("#"+subgrid_table_id).width()+27<$(".mygrid2").width()){
                $("#"+subgrid_table_id).jqGrid('setGridWidth', $(".mygrid2").width()-27);
            }
            $("#"+subgrid_table_id).parent().parent().width($("#"+subgrid_table_id).width()+2);
            $("#"+subgrid_table_id).parent().parent().prev().width($("#"+subgrid_table_id).width()+2);
        }
        jQuery("#mygrid2").jqGrid('setGridWidth', $("#mygrid2_1_t").width()+27);
        jQuery("#mygrid2").jqGrid('setGridHeight', totalLines*30+3*(matinfo.length+1));
    }
    $(window).resize(function(){
        resize();
    });
    resize();
}

// 最低总价评标
function grdLowestSumPrice2(datalist){
    var colNames = ['ID','供应商名称','总价(RMB)','是否最低价','排名','备注'];
    var rows = [];   // 所有行数据
    var groupHeaders = [];
    var colModel = [
        {name:'splrId',index:'splrId', width:50,hidden: true},
        {name:'splrNam',index:'splrNam', width:150,frozen:true},
        {name:'ttlPri',index:'ttlPri', width:80,align:"center",frozen:true},
        {name:'isLowest',index:'isLowest',width:80,align:'center'},
        {name:'grdOrd',index:'grdOrd', width:70,frozen:true,formatter:'number'},
        {name:'grdRsn',index:'grdRsn', width:150,frozen:true}
    ];
    if(datalist.length){
        for(var i=0;i<datalist.length;i++){
            var splrId = datalist[i].splrId;
            var ids = [];
            datalist[i].grdOrd = datalist[i].grdOrd ? datalist[i].grdOrd : i+1;
            datalist[i].isLowest = i==0 ? "是":"否";
            for(var m=0;m<datalist[i].qotInfs.length;m++){
                var matinfo = datalist[i].qotInfs[m];
                console.log('-----',i,m,splrId);
                if(i==0){
                    groupHeaders.push({startColumnName:"uniPri"+m,numberOfColumns:3,titleText:matinfo.matNam});
                    colNames.push("单价");
                    colNames.push("数量");
                    colNames.push("币种");
                    colModel.push({name:"uniPri"+m,index:"uniPri"+m,align:'center',width : 60,sortable : false});
                    colModel.push({name:"splNum"+m,index:"splNum"+m,align:'center',width : 60,sortable : false});
                    colModel.push({name:"currTyp"+m,index:"currTyp"+m,align:'center',width : 60,sortable : false,formatter: currTypFmatter});
                }
                datalist[i]["uniPri"+m] = matinfo.uniPri;
                datalist[i]["splNum"+m] = matinfo.splNum;
                datalist[i]["currTyp"+m] = matinfo.currTyp;
                datalist[i]["matId"+m] = matinfo.matId;
                datalist[i]["matNam"+m] = matinfo.matNam;
                ids.push(matinfo.id);
            }
            rows.push(datalist[i]);
        }
    }
    $("#mygrid3").jqGrid({
        width:'100%',
        height:'100%',
        dataType:'local',
        colNames:colNames,
        colModel:colModel,
        viewrecords:true,
        rowNum:-1,
        fitColumns: true,
        shrinkToFit: true,
        altRows: true,
        cellEdit: true,
        cellsubmit: 'clientArray',
        onSelectRow : function(id) {
            if (id && id !== lastsel) {
                jQuery("#"+subgrid_table_id).jqGrid('saveRow', lastsel);
                lastsel = id;
            }
        },
        afterEditCell: function(a, b, c, d, e) { },
        formatCell: function(a, b, c, d, e) { },
        beforeSubmitCell: function(a, b, c, d, e) { },
        beforeSaveCell: function(a, b, c, d, e) { },
        afterSaveCell: function(a, b, c, d, e) { }
    });
    $("#mygrid3").jqGrid('setGroupHeaders', {
        useColSpanStyle: true,
        groupHeaders:groupHeaders
    });
    for ( var i = 0; i < rows.length; i++){
        var rowid = i + 1;
        $("#mygrid3").jqGrid('addRowData', rowid, rows[i]);
        $("#mygrid3 #"+rowid).data("rowinfo",rows[i]);
    }

    function resize(){
        if($("#mygrid3").width()< $(".mygrid3").width()){
            $("#mygrid3").jqGrid('setGridWidth', $(".mygrid3").width()-20);
        }
        jQuery("#mygrid3").jqGrid('setGridHeight', (rows.length)*32);
    }
    $(window).resize(function(){
        resize();
    });
    resize();
}





















//
// import resultsListTpl from "./results_list.handlebars";
// import paginationTpl from "./paging.handlebars";
//
// var ResultsList = {
//     pageNo: 1,
//     pageSize: 20,
//     maxPage: 1,
//     isFirstPage: false,
//     isLastPage: false,
//     total: 0,
//     init: function(){
//         this.getResultsData()
//             .then(this.renderResultsList)
//             .then(this.renderPagination)
//             .then(this.bindEvent);
//     },
//     getResultsData: function() {
//         return new Promise((resolve, reject)=>{
//             let self = this;
//             $.ajax({
//                 url: HOST_ADDR + `/cpmp/bidProjOnMngForPchs/getGrdDtls/${self.pageNo}/${self.pageSize}/`+grdId,
//                 type: 'get',
//                 dataType: 'json',
//                 headers: {
//                     'access_token': token,'login_type':'ums'
//                 },
//                 contentType: "application/json",
//                 success: function (resp) {
//                     if (resp.success) {
//                         console.log(resp);
//                         resolve(resp);
//                     }
//                     else {
//                         alert(resp.msgInf);
//                     }
//                 },
//                 error: function (err) {
//                     console.log(err);
//                 }
//             });
//         });
//     },
//     // 渲染列表
//
//     renderResultsList: function(resp){
//         let self = ResultsList;
//         // 处理数据begin
//         self.total = resp.data.count;
//         self.isFirstPage = self.pageNo === 1;
//         self.maxPage = Math.ceil(self.total / self.pageSize);
//         // 处理数据end
//         if(self.pageNo * self.pageSize >= self.total){
//             self.isLastPage = true;
//         }else{
//             self.isLastPage = false;
//         }
//         let resultHtml = resultsListTpl({ResultsList: resp.data.list});
//         $('.J_grid-results').html(resultHtml);
//     },
//
//     // 渲染分页
//     renderPagination: function(){
//         let self = ResultsList;
//         let pageList = [];
//         for(let i=0; i<self.maxPage; i++){
//             pageList.push({idx: i+1});
//         }
//         console.log(self.total);
//         let paginationHtml = paginationTpl({
//             begin: (self.pageNo-1) * self.pageSize + 1,
//             end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
//             total: self.total,
//             isLastPage: self.isLastPage,
//             isFirstPage: self.isFirstPage,
//             pageList: pageList
//
//         });
//         $('.J_pagination').html(paginationHtml);
//         $('.page-item').each((index,item)=>{
//             if($(item).data('index')===self.pageNo){
//                 console.log(this);
//                 $(item).addClass('active');
//             }
//             //最多显示7个页码
//             if (Math.abs($(item).data('index')-self.pageNo) > 3) {
//                 $(item).css('display','none');
//             }
//         });
//     },
//
//     // 绑定事件
//     bindEvent: function(){
//         let self = ResultsList;
//         $('.J_prev').unbind().click(function(){
//             if(self.pageNo > 1){
//                 self.pageNo = self.pageNo -1;
//                 self.renderList();
//             }
//         });
//         $('.J_next').unbind().click(function(){
//             if(self.pageNo < self.maxPage){
//                 self.pageNo = self.pageNo + 1;
//                 self.renderList();
//             }
//         });
//
//         //首尾页
//         $('.isFirst').unbind().click(function(){
//             if(self.pageNo != 1){
//             self.pageNo = 1;
//             self.renderList();
//             }
//         });
//         $('.isLast').unbind().click(function(){
//             if(self.pageNo != self.maxPage){
//                 self.pageNo = self.maxPage;
//                 self.renderList();
//             }
//         });
//
//         $('.page-item').unbind().click(function(){
//             let $item = $(this);
//             if(!$item.hasClass('active')){
//                 self.pageNo = $item.data('index');
//                 self.renderList();
//             }
//         });
//     },
//
//     // 渲染列表
//     renderList(){
//         this.getResultsData()
//             .then(this.renderResultsList)
//             .then(this.renderPagination)
//             .then(this.bindEvent);
//     }
// };
//
// ResultsList.init();
//